﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Microhard.FMCG.VerFakeCodeGenerator
{
    public partial class LabelForm : Form
    {
        string savePath = "";
        string codePath = "";
        int numImage = 0;
        Thread SecondThread = null;

        public LabelForm(string codepath, int numimage)
        {
            InitializeComponent();

            codePath = codepath;
            numImage = numimage;

            if (string.IsNullOrEmpty(codePath))
            {
                codePath = System.Configuration.ConfigurationManager.AppSettings["CodePath"];
            }
            if (numImage == 0)
            {
                numImage = int.Parse(System.Configuration.ConfigurationManager.AppSettings["EndNum"]);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (this.folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                savePath = this.folderBrowserDialog1.SelectedPath + "\\";
                textBox1.Text = savePath;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SecondThread = new Thread(new ThreadStart(PrintLabels));
            SecondThread.Start();

        }

        public void CloseTask()
        {
            if (SecondThread != null)
            {
                SecondThread.Abort();
            }
        }

        void PrintLabels()
        {
            for (int i = 1; i <= numImage; i++)
            {
                System.Drawing.Image image1 = System.Drawing.Image.FromFile("Images/Template.jpg", true);
                System.Drawing.Image image2 = System.Drawing.Image.FromFile(codePath + i.ToString() + ".png", true);

                System.Drawing.Size size = new System.Drawing.Size((int)image1.Width, (int)image1.Height);
                System.Drawing.Image bitmap = new System.Drawing.Bitmap(size.Width, size.Height);
                System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

                g.DrawImage(image1, 0, 0);
                g.DrawImage(image2, new System.Drawing.Rectangle(2150, 50, 800, 800));

                Font ft = new Font("Times New Roman", 50);
                g.DrawString(i.ToString(), ft, new SolidBrush(Color.Black), 2540, 850);
                bitmap.Save(savePath + i.ToString() + ".Jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
                bitmap.Dispose();
                g.Dispose();
            }

            MessageBox.Show("生成标签成功！");
        }

        private void LabelForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.CloseTask();
        }
    }
}
